package cn.chanel.mall.admin.controller;

import cn.chanel.mall.admin.conf.AdminAccountConfig;
import cn.chanel.mall.constant.CookieName;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/admin/login")
public class AdminLoginController {

    @Resource
    private AdminAccountConfig adminAccountConfig;

    @GetMapping
    public ModelAndView adminLogin(){
        return new ModelAndView("/admin/login/login");
    }

    @PostMapping
    public ModelAndView adminLogin(@RequestParam(required = false, defaultValue = "") String username,
                                   @RequestParam(required = false, defaultValue = "") String password,
                                   Map<String, Object> map,
                                   HttpServletRequest request){
        if(StringUtils.hasText(username) && StringUtils.hasText(password)){
            if(adminAccountConfig.getUsername().equals(username) &&
                    adminAccountConfig.getPassword().equals(password)){
                final HttpSession session = request.getSession();
                session.setAttribute(CookieName.ADMIN_LOGIN, username.hashCode());
                session.setMaxInactiveInterval(180); // 3Min
                return new ModelAndView("redirect:/admin/goods/list");
            }
        }
        map.put("msg", "用户名或者密码错误");
        map.put("url", "redirect:/admin/login");
        return new ModelAndView("/admin/common/error", map);
    }
}
